<?php

namespace App\Http\Controllers\Receivemoney;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Receivemoney\Receivemoney;
use App\Models\Balance\Balance;
use App\Models\Company;
use App\Models\Custom\Custom;
use App\Models\Manger\Manger;
use App\Models\Order\Outboundorderwithpay;
use App\Models\Receivemoney\Receipt;
use App\Models\Receivemoney\Receivemoney as ModelReceivemoney;
use App\Models\Settle\SettleCompany;
use App\Models\Settle\SettleType;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\Common;
use App\Services\Common\SnCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

/**
 * 认领单管理
 */
class ReceivemoneyController extends BaseController
{
    /***
     *  统审端-发款池，创建认款单（统审角色 隶属于账套）
     *  销售端-认款池，认领。认款池为公共认款池，销售可看到别人的认领单
     *
     *  认领成功，生成收款列表
     *
     *  发出认领单，业务员_公司名称_结算公司名称。每个业务员（销售）都可能办理同一家公司业务
     *
     *  认领单的公司名称=基础信息（结算客户）的公司名称（非往来单位名称） 2025.05.09 王丹娜
     *
    */

    /**
     * 添加 财务端
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'firm_name',
            'amount',
            'date',
            'settlement_company',
            'bank_name',
            'settlement_category',
            'settlement_category_id',
            'notes'
        ]);
        $validate = new Receivemoney('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;

        $req_data['settlement_category'] = SettleType::where(['id' => $req_data['settlement_category_id'],'cpid' => $cpid])->value('type_name');

        /***
         * 检查结算公司/公司名称 客户信息，是否存在
         */
//        $checkClaim = $this->checkClaimForm(['settlement_company_name'=>$req_data['settlement_company'],'firm_name'=>$req_data['firm_name']]);
//        if($checkClaim['code'] != '000'){
//            return response()->json($checkClaim);
//        }
        $org_firm_name = $req_data['firm_name']; //原公司名，需求为了 统审方便查看不同业务员

//        2025-09-11修改为纯填写  写啥展示啥
//        $firm_name_arr = explode('_',$req_data['firm_name']);
//        $firm_name = $firm_name_arr[1];//真实公司名

        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'firm_name' => $org_firm_name,
            'tplus_company_name' => '',
            'amount' => $req_data['amount'],
            'date' => $req_data['date'],
            'settlement_company' => $req_data['settlement_company'],
            'bank_name' => $req_data['bank_name'],
            'settlement_category' => $req_data['settlement_category'],
            'settlement_category_id' => $req_data['settlement_category_id'],
            'notes' => $req_data['notes'],
            'status' => config('constants.receive_money.waiting_sent_out'),
            'create_at' => time(),
        ];
        ModelReceivemoney::create($data);
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id',
            'firm_name',
            'amount',
            'date',
            'settlement_company',
            'bank_name',
            'settlement_category',
            'settlement_category_id',
            'notes'
        ]);
        $validate = new Receivemoney('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;

        $req_data['settlement_category'] = SettleType::where(['id' => $req_data['settlement_category_id'],'cpid' => $cpid])->value('type_name');
        /***
         * 检查结算公司/公司名称 客户信息，是否存在
         */
//        $checkClaim = $this->checkClaimForm(['settlement_company_name'=>$req_data['settlement_company'],'firm_name'=>$req_data['firm_name']]);
//        if($checkClaim['code'] != '000'){
//            return response()->json($checkClaim);
//        }
        $org_firm_name = $req_data['firm_name'];
//        $firm_name_arr = explode('_',$req_data['firm_name']);
//        $firm_name = $firm_name_arr[1];

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'firm_name' => $org_firm_name,
            'tplus_company_name' => '',
            'amount' => $req_data['amount'],
            'date' => $req_data['date'],
            'settlement_company' => $req_data['settlement_company'],
            'bank_name' => $req_data['bank_name'],
            'settlement_category' => $req_data['settlement_category'],
            'settlement_category_id' => $req_data['settlement_category_id'],
            'notes' => $req_data['notes'],
            'update_at' => time(),
        ];
        ModelReceivemoney::where([['id', $req_data['id']]])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 发出认领单
     */
    public function sentout(Request $request)
    {
        $req_data = $request->only(['id']);
        $validate = new Receivemoney('sentout');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        //修改状态
        $data = [
            'status' => config('constants.receive_money.sent_out'),
            'update_at' => time(),
        ];
        ModelReceivemoney::where([['id', $req_data['id']]])->update($data);

        $cpid = $this->mangerinfo['cpid'] ?? 0;
        //给本cpid下的所有utype=7业务员加小红点
        $list = Manger::where(['utype' => 7, 'cpid' => $cpid])->get()->toArray();
        $key = 'receivemoney_manger_' . $cpid;
        if ($list) {
            foreach ($list as $item) {
                Redis::hset($key, $item['id'], 1);
            }
        }

        return response()->json(['code' => '000', 'msg' => '发出成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $key = 'receivemoney_manger_' . $cpid;
        //消除小红点
        Redis::hset($key, $manger_id, 2);

        $isgetall = $request->isgetall ?? 0;
        $list = ModelReceivemoney::getList($request, $mangerinfo, $isgetall);
        // if ($list['list']) {
        //     foreach ($list['list'] as $key => $value) {
        //         $list['list'][$key]['amount'] = $value['amount'] / 100;
        //     }
        // }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelReceivemoney::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '认领单不存在']);
        }
        $one = $one->toArray();
        $one['amount'] = $one['amount'] / 100;
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 红点
     */
    public function redpoint()
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $key = 'receivemoney_manger_' . $cpid;
        //1红点 2无红点
        $redpoint = Redis::hget($key, $manger_id);
        if ($redpoint == false) $redpoint = 2;
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['redpoint' => $redpoint]]);
    }

    /**
     * 认领 业务员端
     */
    public function claimed(Request $request)
    {
        $req_data = $request->only(['id']);
        $validate = new Receivemoney('claimed');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $receivemoney = ModelReceivemoney::where([['id', $req_data['id']]])->first();
        if (!$receivemoney) {
            return response()->json(['code' => '001', 'msg' => '认款单不存在']);
        }
        $receivemoney = $receivemoney->toArray();
        if ($receivemoney['status'] != config('constants.receive_money.sent_out')) {
            return response()->json(['code' => '001', 'msg' => '认款单不是已发送状态']);
        }

        //判断是否有认领资格，公司名称
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $realname = $mangerinfo['realname'];

        //判断公司名称+结算公司
        $settleCompanyId = SettleCompany::query()
            ->where(['settle_company_name'=>$receivemoney['settlement_company'],'cpid'=>$cpid])
            ->value('id') ?? 0;
        if ($settleCompanyId <= 0) {
            return response()->json(['code' => '001', 'msg' => '您不具备认领资格，请确认后再认领']);
//            return response()->json(['code' => '001', 'msg' => '认领失败']);
        }
        // 根据结算公司id查询
        $custom = Custom::where('manger_id', $manger_id)
            ->where('firm_name', $receivemoney['firm_name'])
            ->where('settlement_company', $settleCompanyId)
            ->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '没有认领资格']);
        }
        if($custom->custom_status !='3' || $custom->invoice_status !='3'){
            return response()->json(['code' => '001', 'msg' => '无法认领,客户未审核成功']);
        }
        if($custom->is_freeze =='2'){
            return response()->json(['code' => '001', 'msg' => '无法认领,客户被冻结']);
        }

        $custom = $custom->toArray();

        DB::beginTransaction();
        try {
            //认领
            $data = [
                'receiver_id' => $manger_id,
                'status' => config('constants.receive_money.claimed'),
                'receiver_at' => time(),
                'update_at' => time(),
            ];
            ModelReceivemoney::where([['id', $req_data['id']]])->update($data);

            //账户余额加钱
            Balance::where([['custom_id', $custom['id']], ['manger_id', $manger_id]])
                ->increment('balance', $receivemoney['amount']);

            //生成收款单
            $sk_code = SnCode::getSnCode('SK_');
            $date = time();

            if (is_numeric($custom['settlement_company'])) {
                $settlement_company = SettleCompany::where([['id', (int)$custom['settlement_company']]])->first();
                if ($settlement_company) {
                    $settlement_company = $settlement_company->toArray();
                    $settlement_company_name = $settlement_company['settle_company_name'];
                } else {
                    $settlement_company_name = '';
                }
            } else {
                $settlement_company_name = $custom['settlement_company'];
            }

            $data = [
                'cpid' => $cpid,
                'order_receiver_id' => $req_data['id'],
                'date' => $date,
                'code' => $sk_code,
                'category' => 1, //1预收款
                'custom_name' => $realname . '-' . $custom['company_name'] . '*' . $settlement_company_name,
                'settlement_category' => $receivemoney['settlement_category'], //结算方式
                'settlement_category_id' => $receivemoney['settlement_category_id'], //结算方式id
                'settlement_company' => $settlement_company_name,
                'bank_name' => $receivemoney['bank_name'],
                'amount' => $receivemoney['amount'],
                'notes' => $receivemoney["notes"],
                'create_at' => $date,
                'manger_id' => $manger_id //增加认领人id 2025.04.03
            ];
            $ReceiptId = Receipt::create($data)->id;
            $ChanjetData = $data;
            //生成出库收款对账单
            $data2 = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'type' => 2,
                'document_number' => $sk_code,
                'order_date' => $date,
                'money' => $receivemoney['amount'],
                'custom_id' => $custom['id'],
                'settlement_company' => $custom['settlement_company'],
                'create_at' => $date
            ];
            Log::info('收款单:' . json_encode($data2));
            Outboundorderwithpay::create($data2);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '认领失败' . $e->getMessage()]);
        }
        //            if($this->mangerinfo['org_id']) {
        //                $Chanjet_param = [
        //                    "dto" => [
        //                        "VoucherDate" => date('Y-m-d',$chanjetData['date']),
        //                        "ExternalCode" => $chanjetData['code'],
        //                        "Partner" => ["Name" => $chanjetData['custom_name']],//往来单位编码
        //                        //"Department" => ["Code" => ""],//部门
        //                        "IsReceiveFlag" => "True",//赋值为true，则为收款单;赋值为false，则为付款单
        //                        "BusiType" => '34',//收款单时，包括33（普通收款），34（预收款）和45（直接收款）；
        //                        "ArapMultiSettleDetails" => [ //核销明细
        //                            "SettleStyle" => ["code" => ""],//网银code
        //                            "BankAccount" => ["name" => $chanjetData['bank_name']],
        //                            "OrigAmount" => $chanjetData['amount'],
        //                        ]
        //                    ]
        //                ];
        //                ChanjetRequest::getInstance()->ReceivePaymentVoucherOpenApiNewCreate($Chanjet_param,$this->mangerinfo['org_id']);
        //            }

        $Chanjet_param = [
            'type' => 'receivemoney',
            'ChanjetData' => $ChanjetData,
            'custom' => $custom,
            'receivemoney' => $receivemoney,
        ];
        $requestData = [
            "api" => "ReceivePaymentVoucherOpenApiNewCreate",
            "param" => $Chanjet_param,
            "mangerinfo" => $this->mangerinfo
        ];
        \App\Jobs\ReceiptPayment::dispatch($requestData);

//        //收款单
//        if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//            //创建账号和结算方式
//            $BankAccountCode = common::getPinyin($ChanjetData["settlement_company"]).'_'.common::getPinyin($ChanjetData['bank_name']);
//            $BankAccountName = $ChanjetData["settlement_company"].'_'.$ChanjetData['bank_name'];//结算公司+银行名称
//
//            TplusCommonController::createBankAccount($BankAccountCode,$BankAccountName,$this->mangerinfo["org_id"]);
//
//            $Chanjet_param = [
//                "dto" => [
//                    "VoucherDate" => date('Y-m-d', $ChanjetData['date']),
//                    "Code" => $ChanjetData['code'],
//                    "IsModifiedCode" => "true",
//                    "ExternalCode" => $ChanjetData['code'],
//                    "Partner" => ["Code" => $custom['company_code']], //往来单位编码
//                    "Department" => ["Code" => $mangerinfo['sys_dpm_id']],//部门
//                    "IsReceiveFlag" => "true", //赋值为true，则为收款单;赋值为false，则为付款单
//                    "BusiType" => ["Code" => "34"], //收款单时，包括33（普通收款），34（预收款）和45（直接收款）；
//                    "ArapMultiSettleDetails" => [ //多结算明细 结算方式取网银
//                        "SettleStyle" => ["code" => SettleType::where('id', $receivemoney["settlement_category"])->value("type_no")], //网银code 认款单
////                        "SettleStyle" => ["code" => SettleType::where('id', $receivemoney["settlement_category"])->value("type_no")], //网银code 认款单
//                        "BankAccount" => ["name" => $BankAccountName],
//                        "OrigAmount" => $ChanjetData['amount'] / 100,
//                    ]
//                ]
//            ];
//            ChanjetRequest::getInstance()->ReceivePaymentVoucherOpenApiNewCreate($Chanjet_param, $this->mangerinfo['org_id']);
//        }
        return response()->json(['code' => '000', 'msg' => '认领成功']);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $id = $request['id'] ?? 0;
        $receivemoney = ModelReceivemoney::where([['id', $id]])->first();
        if (!$receivemoney) {
            return response()->json(['code' => '001', 'msg' => '认款单不存在']);
        }

        ModelReceivemoney::where([['id', $id]])->update([
            'is_del' => config('constants.is_del.yes'),
            'update_at' => time()
        ]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 撤回
     */
    public function recall(Request $request)
    {
        $id = $request['id'] ?? 0;
        $receivemoney = ModelReceivemoney::where([['id', $id]])->first();
        if (!$receivemoney) {
            return response()->json(['code' => '001', 'msg' => '认款单不存在']);
        }

        $receivemoney = $receivemoney->toArray();
        //未认领的才能撤回
        if ($receivemoney['status'] != config('constants.receive_money.sent_out')) {
            return response()->json(['code' => '001', 'msg' => '未认领的单子才能撤回']);
        }

        ModelReceivemoney::where([['id', $id]])->update([
            'status' => config('constants.receive_money.waiting_sent_out'),
            'update_at' => time()
        ]);
        return response()->json(['code' => '000', 'msg' => '撤回成功']);
    }

    /**
     * 平账
     */
    public function move(Request $request)
    {
        $req_data = $request->only([
            'id',
            'receiver_id',
            'new_receiver_id',
            'firm_name',
            'settlement_company',
            'amount'
        ]);
        $validate = new Receivemoney('move');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $settleCompanyId = $this->getSettleCompanyId($req_data);
        if (!$settleCompanyId) {
            return response()->json(['code' => '001', 'msg' => '获取结算公司失败']);
        }
        //判断新认款人是否有资格
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $custom = Custom::where('manger_id', $manger_id)
            ->where('company_name', $req_data['firm_name'])
            ->where('settlement_company', $settleCompanyId)
            ->first();
        if (!$custom) {
            return response()->json(['code' => '001', 'msg' => '没有认领资格']);
        }
        $check_new_receiver_id = Manger::where('id',$req_data['new_receiver_id'])->first();
        if(!$check_new_receiver_id){
            return response()->json(['code' => '001', 'msg' => '转款人信息不存在']);
        }

        //更新人员信息
        DB::beginTransaction();
        try {
            $id = $req_data['id'];
            ModelReceivemoney::where([['id', $id]])->update([
                'receiver_id' => $req_data['new_receiver_id'],
                'update_at' => time()
            ]);
            /***
             * 更新
             *
            */

            //减余额
            Balance::where([['custom_id', $req_data['receiver_id']], ['cpid', $cpid]])
                ->decrement('balance', $req_data['amount']);
            //加余额
            Balance::where([['custom_id', $req_data['new_receiver_id']], ['cpid', $cpid]])
                ->increment('balance', $req_data['amount']);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '平账失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '平账成功']);
    }
    protected function getSettleCompanyId($data = []){
        if(!isset($data["settlement_company"])){
            return 0;
        }
        $settleCompanyId = $data['settlement_company'];//前端传值 可能中文/数字
        if (!is_numeric($settleCompanyId)) {
            $settleCompanyId = SettleCompany::where('settle_company_name', $data['settlement_company'])
                ->value('id');
        }
        return $settleCompanyId;
    }
    /***
     *
     *  检查认领单是否合法
     *
    */
    public function checkClaimForm($data = []){
        $manger_id = $this->mangerinfo['id'];
        $cpid = $this->mangerinfo['cpid'];

        $res = ['code' => '001','msg' => ''];
        if(empty($data['settlement_company_name'])){
            $res['msg'] = "结算公司名称不存在";
            return $res;
        }
        if(empty($data['firm_name'])){
            $res['msg'] = "公司名称不存在";
            return $res;
        }
        $firm_name_arr = explode('_',$data['firm_name']);
        if(count($firm_name_arr) != 3 || empty($firm_name_arr[1])){
            $res['msg'] = "公司名称非法";
            return $res;
        }
        $firm_name = $firm_name_arr[1];

        $settleCompany = SettleCompany::where([
            'cpid' => $cpid,'settle_company_name' => $data['settlement_company_name'],
            'status' => '1'
        ])->first();
        if(!$settleCompany){
            $res['msg'] = "结算公司不存在";
            return $res;
        }
        $custom = Custom::where(['settlement_company' => $settleCompany['id'],'firm_name' => $firm_name,
            'manger_id' => $manger_id])->first();
        if(!$custom){
            $res['msg'] = "客户信息不存在";
            return $res;
        }
        $res['code'] = '000';
        return $res;
    }
}
